package com.rong.shop.service.impl;

import com.rong.shop.mapper.UserMapper;
import com.rong.shop.pojo.User;
import com.rong.shop.service.IUserService;
import com.rong.shop.service.ex.*;
import com.rong.shop.utils.RongUtils;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;

    /**
     * 用户注册
     * @param user
     */
    @Override
    public void reg(User user) {

        String username = user.getUsername();
        User result = userMapper.findByUsername(username);
        // -->在注册前先检测用户名是否被占用
        if(result != null){

            throw new UsernameDuplicatedException("用户名被占用");

        }

        // -->没有被占用，正常注册

        //	isDelete  '是否删除：0-未删除，1-已删除', 默认为0
        user.setIsDelete(0);

        // 四个字段的初始化 createdUser; createdTime; modifiedUser; modifiedTime;
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        user.setCreatedTime(new Date());
        user.setModifiedTime(new Date());

        // MD5 盐值加密 --》  (salt + pwd + salt) 三次加密
        String oldPwd = user.getPassword();
        String salt = UUID.randomUUID().toString().toUpperCase();

        String newPwd = RongUtils.md5SEncrypt(oldPwd, salt);
        user.setPassword(newPwd);
        user.setSalt(salt);

        Integer rows = userMapper.addUser(user);
        if (rows < 1) {
            throw new InsertException("用户添加失败");
        }


    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {

        // 首先判断账号是否存在，或者是否被删除
        User result = userMapper.findByUsername(username);

        if(result == null || result.getIsDelete() == 1){
            throw new NotFoundUserException("该用户没有找到...");
        }

        // 密码校验
        String oldPwd = result.getPassword(); //数据库里加密的密码
        String salt = result.getSalt();
        String newOld = RongUtils.md5SEncrypt(password, salt); //用 输入的密码 进行获取的 新密码

        // 密码错误抛出异常
        if(!newOld.equals(result.getPassword())){
            throw new PasswordErrorException("密码错误");
        }

        // 创建VO对象，用以前端传输数据
        User userVO = new User();
        userVO.setUid(result.getUid());
        userVO.setUsername(result.getUsername());
        userVO.setAvatar(result.getAvatar());

        return userVO;
    }

    /**
     * 根据 uid 获取用户
     * @param uid  前端传来的UID
     * @return     返回用户对象
     */
    @Override
    public User getUserByUid(int uid) {
        User u = userMapper.findByUid(uid);
        if(u == null || u.getIsDelete() == 1){
            throw new NotFoundUserException("没有找到该用户");
        }

        User userVO = new User();
        userVO.setUid(u.getUid());
        userVO.setUsername(u.getUsername());
        userVO.setPhone(u.getPhone());
        userVO.setEmail(u.getEmail());
        userVO.setGender(u.getGender());

        return userVO;
    }

    /**
     * 根据UID 修改用户密码
     * @param uid       查询
     * @param username  操作用户
     * @param oldPwd    进行校验
     * @param newPwd    进行加密后更新
     */
    @Override
    public void changePwd(int uid, String username, String oldPwd, String newPwd) {

        User subject = userMapper.findByUid(uid);

        // 如果没查找到用户，或者用户被删除；则抛出异常
        if(subject == null || subject.getIsDelete() == 1){
            throw new NotFoundUserException("没有找到用户");
        }

        // 判断用户的密码，与传递过来的密码是否一致
        String oldMd5Pwd = RongUtils.md5SEncrypt(oldPwd, subject.getSalt());
        if(!subject.getPassword().equals(oldMd5Pwd)){
            throw new PasswordErrorException("原密码错误");
        }

        // 进行密码的更新（加密后）
        String newMd5Pwd = RongUtils.md5SEncrypt(newPwd, subject.getSalt());
        Integer rows = userMapper.updatePwdByUid(uid, newMd5Pwd, username, new Date());
        if(rows < 1){
            throw new UpdateException("更新时发生未知的错误");
        }
    }

    /**
     * 根据uid 修改用户头像
     * @param uid           通过session传递的-》用户id
     * @param username      通过session传递的-》操作人
     * @param avatar        前端传来的avatar 字节串
     */
    @Override
    public void changeAvatar(int uid, String username, String avatar) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete() == 1){
            throw new NotFoundUserException("没有找到该用户");
        }

        Integer rows = userMapper.updateAvatarByUid(result.getUid(), avatar, result.getUsername(), new Date());
        if(rows < 1){

            throw new UpdateException("更新异常");

        }

    }

    /**
     * 根据uid 修改用户信息
     * @param uid       通过session传递的-》用户id
     * @param username  通过session传递的-》操作人
     * @param user      根据前端传来的user 字段
     */
    @Override
    public void changeInfo(int uid, String username, User user) {
        User result = userMapper.findByUid(uid);
        if(result == null || result.getIsDelete() == 1){
            throw new NotFoundUserException("没有找到该用户");
        }

        // 只需要 email phone gender ModifiedTime ModifiedUser 五个字段
        User userVO = new User();
        userVO.setUid(uid);
        userVO.setEmail(user.getEmail());
        userVO.setGender(user.getGender());
        userVO.setPhone(user.getPhone());
        userVO.setModifiedUser(username);
        userVO.setModifiedTime(new Date());

        Integer rows = userMapper.updateInfoByUid(userVO);
        if(rows < 1){
            throw new UpdateException("更新时发生未知异常");
        }
    }


}
